﻿using CoachingOrganizer.Database.DataAccess;
using CoachingOrganizer.Toolkit.Events;
using SQLite.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CoachingOrganizer.Database
{
    public abstract class DbManagerBase
    {
        private readonly SQLiteConnection _context;

        public SQLiteConnection Context
        {
            get { return _context; }
        }

        public DbManagerBase()
        {
            _context = new SQLiteConnection(GetPlatform(), GetDataFolder());
            _context.CreateTable<PeriodDA>();
            _context.CreateTable<GoalDA>();
            _context.CreateTable<MoodLevelDA>();
            _context.CreateTable<MoodValueDA>();
            _context.CreateTable<EmotionsPackDA>();
            _context.CreateTable<EmotionTraceItemDA>();
            _context.CreateTable<MoneyCalculationDA>();
            _context.CreateTable<StableMoneyFlowItemDA>();
            _context.CreateTable<OccasionalMoneyFlowItemDA>();
        }

        public ActionResult<TResult> SafeRequest<TResult>(Func<TResult> delegateToRun)
        {
            try
            {
                TResult result = delegateToRun();
                return ActionResult<TResult>.GetValidResult(result);
            }
            catch (SQLiteException ex)
            {
                return ActionResult<TResult>.GetErrorResult(ex);
            }
        }

        public ActionResult SafeRun(Action delegateToRun)
        {
            try
            {
                delegateToRun();
                return ActionResult.ValidResult;
            }
            catch (SQLiteException ex)
            {
                return ActionResult.GetErrorResult(ex);
            }
        }

        protected abstract SQLite.Net.Interop.ISQLitePlatform GetPlatform();

        protected abstract string GetDataFolder();
    }
}
